package com.un.ebs.core.util;

import com.un.ebs.core.metadata.ServiceInfo;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author liubo
 * @email liubocs@163.com
 * @date 2020/4/8 17:52
 */
public class CodeGenUtils {

    public static void codeGenByApiJs(String packageName) throws IOException {
        List<ServiceInfo> list = PackageUtil.getControllers(packageName);
        if (StringUtils.isNullOrEmpty(list)) {
            return;
        }
        for (ServiceInfo s : list) {
            codeGenByApiJs(s);
        }
    }

    public static void codeGenByApiJs(Class<?> cls) throws IOException {
        codeGenByApiJs(PackageUtil.getController(cls));
    }

    public static void codeGenByApiJs(ServiceInfo obj) throws IOException {
        if (obj == null) {
            return;
        }
        if (StringUtils.isNullOrEmpty(obj.getFunctions())) {
            return;
        }
        VelocityEngine engine = new VelocityEngine();
        VelocityContext context = new VelocityContext();

        File file = new File("/" + obj.getName() + ".js");
        FileWriter fw = new FileWriter(file, false);

        engine.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CodeGenUtils.class.getResource("/templates").getPath());
        Template template = engine.getTemplate("api.js.vm");

        BufferedWriter write = new BufferedWriter(fw);
        context.put("svc", obj);
        context.put("currTime", DateUtils.formatDate(new Date(), "yyyy.M.d HH:ss"));
        template.merge(context, write);
        write.flush();
        write.close();

        LoggerFactory.getLogger(CodeGenUtils.class).debug(String.format("%s.js 已经生成", obj.name));
    }
}
